<template>
  <div class="homework-main">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">{{ student?.name || '小朋友' }}作业计划表</h1>
      <div class="header-actions">
        <!-- 学生信息管理按钮 -->
        <el-button
          v-if="!student"
          type="warning"
          @click="showStudentDialog = true"
        >
          <el-icon><user /></el-icon>
          添加学生信息
        </el-button>
  
        <el-button
          v-if="!authStore.isLoggedIn"
          type="primary"
          @click="showLoginDialog = true"
        >
          管理员登录
        </el-button>
        <template v-else>
          <el-dropdown @command="handleCommand">
            <el-button>
              管理功能<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="student">学生信息管理</el-dropdown-item>
                <el-dropdown-item command="add-homework">添加新作业</el-dropdown-item>
                <el-dropdown-item command="edit">编辑作业</el-dropdown-item>
                <el-dropdown-item command="daily">日常作业管理</el-dropdown-item>
                <el-dropdown-item command="schedule">课程表管理</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </div>
    </div>

    <!-- 当前作业区域 -->
    <div class="current-homework-section">
      <HomeworkList
        :current-homeworks="homeworkStore.currentHomeworks || []"
        :homework-details="homeworkStore.homeworkDetails"
        :is-admin-logged-in="authStore.isLoggedIn"
        @refresh="loadCurrentHomework"
        @edit-homework="handleEditHomework"
        @manage-details="handleManageDetails"
      />
    </div>

    <!-- 课程表区域 -->
    <div class="schedule-section">
      <el-row :gutter="20">
        <el-col :span="18">
          <ClassSchedule
            :student-id="student?.id"
            :is-admin-logged-in="authStore.isLoggedIn"
            @refresh="handleScheduleRefresh"
          />
        </el-col>
        <el-col :span="6">
          <TomorrowClasses
            :student-id="student?.id"
            ref="tomorrowClassesRef"
          />
        </el-col>
      </el-row>
    </div>

    <!-- 数据分析区域 -->
    <div class="analytics-section">
      <!-- 日历和历史分析区域 -->
      <div class="calendar-analysis-container">
        <el-row :gutter="20">
          <!-- 日历组件 -->
          <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
            <Calendar :student-id="student?.id" @date-select="handleDateSelect" />
          </el-col>

          <!-- 历史分析卡片 -->
          <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
            <HistoryAnalysis
              :selected-date="selectedDate"
              :student-id="student?.id"
            />
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="charts-container" style="margin-top: 20px">
        <el-row :gutter="20">
          <el-col :span="12">
            <TrendChart
              title="作业开始时间趋势"
              type="startTime"
              :student-id="student?.id"
            />
          </el-col>
          <el-col :span="12">
            <TrendChart
              title="作业完成时间趋势"
              type="completion"
              :student-id="student?.id"
            />
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 错题本区域 -->
    <div class="mistake-book-section">
      <MistakeBook />
    </div>

    <!-- 管理员登录对话框 -->
    <AdminAuth
      v-model="showLoginDialog"
      mode="login"
      @success="handleLoginSuccess"
    />

    <!-- 作业编辑对话框 -->
    <HomeworkEditor
      v-model="showEditDialog"
      :homework="editingHomework"
      @success="handleEditSuccess"
    />

    <!-- 作业明细编辑对话框 -->
    <HomeworkDetailEditor
      v-model="showDetailDialog"
      :homework="editingHomework"
      @success="handleDetailSuccess"
    />

    <!-- 日常作业管理对话框 -->
    <DailyHomeworkManager v-model="showDailyDialog" />

    <!-- 学生信息管理对话框 -->
    <StudentManager
      v-model="showStudentDialog"
      :student="student"
      @success="handleStudentSuccess"
    />

    <!-- 添加新作业对话框 -->
    <SimpleHomeworkCreator
      v-model="showAddHomeworkDialog"
      @success="handleAddHomeworkSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/store/auth'
import { useStudentStore } from '@/store/student'
import { useHomeworkStore } from '@/store/homework'

// 组件导入
import HomeworkList from './HomeworkList.vue'
import AdminAuth from './AdminAuth.vue'
import HomeworkEditor from './HomeworkEditor.vue'
import HomeworkDetailEditor from './HomeworkDetailEditor.vue'
import DailyHomeworkManager from './DailyHomeworkManager.vue'
import StudentManager from './StudentManager.vue'
import ClassSchedule from './ClassSchedule.vue'
import TomorrowClasses from './TomorrowClasses.vue'
import Calendar from './Calendar.vue'
import HistoryAnalysis from './HistoryAnalysis.vue'
import TrendChart from './TrendChart.vue'
import SimpleHomeworkCreator from './SimpleHomeworkCreator.vue'
import MistakeBook from './MistakeBook.vue'
import { ArrowDown, User, Edit } from '@element-plus/icons-vue'

const authStore = useAuthStore()
const studentStore = useStudentStore()
const homeworkStore = useHomeworkStore()

const showLoginDialog = ref(false)
const showEditDialog = ref(false)
const showDetailDialog = ref(false)
const showDailyDialog = ref(false)
const showStudentDialog = ref(false)
const showAddHomeworkDialog = ref(false)
const editingHomework = ref(null)
const selectedDate = ref(new Date())
const tomorrowClassesRef = ref(null)

const student = computed(() => studentStore.student)

// 加载当前作业
const loadCurrentHomework = async () => {
  if (student.value) {
    try {
      await homeworkStore.fetchCurrentHomework(student.value.id)
    } catch (error) {
      console.error('加载当前作业失败:', error)
    }
  }
}

// 登录成功处理
const handleLoginSuccess = () => {
  ElMessage.success('登录成功')
  showLoginDialog.value = false
}

// 编辑成功处理
const handleEditSuccess = () => {
  // ElMessage.success('作业操作成功')
  // showEditDialog.value = false
  // editingHomework.value = null
  loadCurrentHomework()
}

// 明细编辑成功处理
const handleDetailSuccess = () => {
  ElMessage.success('作业明细操作成功')
  // showDetailDialog.value = false
  // editingHomework.value = null
  loadCurrentHomework()
}

// 处理编辑作业
const handleEditHomework = (homework) => {
  editingHomework.value = homework
  showEditDialog.value = true
}

// 处理管理作业明细
const handleManageDetails = (homework) => {
  editingHomework.value = homework
  showDetailDialog.value = true
}

// 处理课程表刷新
const handleScheduleRefresh = () => {
  // 刷新明日课程
  if (tomorrowClassesRef.value) {
    tomorrowClassesRef.value.refresh()
  }
}

// 学生信息成功处理
const handleStudentSuccess = () => {
  ElMessage.success('学生信息操作成功')
  showStudentDialog.value = false
  // 重新加载当前作业，因为现在有了学生ID
  loadCurrentHomework()
}

// 添加新作业成功处理
const handleAddHomeworkSuccess = () => {
  ElMessage.success('作业添加成功')
  showAddHomeworkDialog.value = false
  // 重新加载当前作业列表
  if (student.value) {
    loadCurrentHomework()
  }
  // 刷新明日课程（如果有）
  if (tomorrowClassesRef.value) {
    tomorrowClassesRef.value.refresh()
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'student':
      showStudentDialog.value = true
      break
    case 'add-homework':
      showAddHomeworkDialog.value = true
      break
    case 'edit':
      handleGlobalEdit()
      break
    case 'daily':
      showDailyDialog.value = true
      break
    case 'schedule':
      handleScheduleManagement()
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理全局编辑
const handleGlobalEdit = () => {
  const currentHomeworks = homeworkStore.currentHomeworks || []

  if (currentHomeworks.length === 0) {
    ElMessage.info('当前没有作业可编辑')
    return
  }

  if (currentHomeworks.length === 1) {
    // 只有一个作业，直接编辑
    editingHomework.value = currentHomeworks[0]
    showEditDialog.value = true
  } else {
    // 多个作业，显示选择菜单
    ElMessageBox.confirm(
      '当前有多个作业，请选择要编辑的作业',
      '选择作业',
      {
        confirmButtonText: '编辑第一个作业',
        cancelButtonText: '取消',
        type: 'info'
      }
    ).then(() => {
      // 选择第一个作业（默认）
      editingHomework.value = currentHomeworks[0]
      showEditDialog.value = true
    }).catch(() => {
      // 用户取消
    })
  }
}

// 登出处理
const handleLogout = async () => {
  try {
    await authStore.logout()
    ElMessage.success('已退出登录')
  } catch (error) {
    console.error('登出失败:', error)
  }
}

// 日期选择处理
const handleDateSelect = (date) => {
  selectedDate.value = date
}

// 定时刷新当前作业
let refreshTimer = null

onMounted(async () => {
  // 加载学生信息
  await studentStore.fetchStudentInfo()

  // 加载当前作业
  await loadCurrentHomework()

  // 设置定时器，每5分钟刷新一次当前作业
  refreshTimer = setInterval(() => {
    loadCurrentHomework()
  }, 5 * 60 * 1000)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.homework-main {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: clamp(20px, 4vw, 28px);
  font-weight: bold;
  color: #2c3e50;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.current-homework-section {
  margin-bottom: 30px;
}

.schedule-section {
  margin-bottom: 30px;
}

.analytics-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.calendar-analysis-container {
  margin-bottom: 20px;
}

.charts-container {
  margin-top: 20px;
}

.mistake-book-section {
  margin-top: 30px;
  margin-bottom: 30px;
}

/* 平板设备适配 */
@media (max-width: 1024px) {
  .homework-main {
    padding: 0 10px;
  }

  .analytics-section {
    padding: 16px;
  }

  .page-header {
    padding: 16px;
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
  }

  .page-title {
    text-align: center;
  }
}

/* 移动设备适配 */
@media (max-width: 768px) {
  .homework-main {
    padding: 0 8px;
  }

  .analytics-section {
    padding: 12px;
  }

  .page-header {
    padding: 12px;
    margin-bottom: 20px;
  }

  .page-title {
    font-size: clamp(18px, 5vw, 24px);
  }

  .current-homework-section,
  .schedule-section {
    margin-bottom: 20px;
  }

  .calendar-analysis-container .el-row,
  .charts-container .el-row {
    margin-left: -10px;
    margin-right: -10px;
  }

  .calendar-analysis-container .el-col,
  .charts-container .el-col {
    padding-left: 10px;
    padding-right: 10px;
    margin-bottom: 16px;
  }
}

/* 小屏幕设备适配 */
@media (max-width: 480px) {
  .homework-main {
    padding: 0 6px;
  }

  .analytics-section {
    padding: 8px;
  }

  .page-header {
    padding: 10px;
    margin-bottom: 16px;
  }

  .page-title {
    font-size: clamp(16px, 6vw, 20px);
  }

  .header-actions {
    gap: 8px;
  }

  .current-homework-section,
  .schedule-section {
    margin-bottom: 16px;
  }

  .calendar-analysis-container .el-row,
  .charts-container .el-row {
    margin-left: -6px;
    margin-right: -6px;
  }

  .calendar-analysis-container .el-col,
  .charts-container .el-col {
    padding-left: 6px;
    padding-right: 6px;
    margin-bottom: 12px;
  }
}

/* 超小屏幕设备适配 */
@media (max-width: 320px) {
  .homework-main {
    padding: 0 4px;
  }

  .analytics-section {
    padding: 6px;
  }

  .page-header {
    padding: 8px;
  }

  .calendar-analysis-container .el-row,
  .charts-container .el-row {
    margin-left: -4px;
    margin-right: -4px;
  }

  .calendar-analysis-container .el-col,
  .charts-container .el-col {
    padding-left: 4px;
    padding-right: 4px;
    margin-bottom: 8px;
  }
}
</style>